// pages/vocabulary/vocabulary.js
Page({
  data: {
    // 学习统计
    todayLearned: 0,
    dailyTarget: 20,
    totalLearned: 0,
    progressPercent: 0,
    
    // 单词书
    currentWordbook: {
      id: 'cet4',
      name: '大学英语四级',
      desc: '大学英语四级核心词汇',
      total: 4500
    },
    wordbookList: [
      {
        id: 'cet4',
        name: '大学英语四级',
        desc: '大学英语四级核心词汇',
        total: 4500
      },
      {
        id: 'cet6',
        name: '大学英语六级',
        desc: '大学英语六级核心词汇',
        total: 6000
      },
      {
        id: 'toefl',
        name: 'TOEFL',
        desc: '托福考试核心词汇',
        total: 8000
      },
      {
        id: 'ielts',
        name: 'IELTS',
        desc: '雅思考试核心词汇',
        total: 7500
      },
      {
        id: 'gre',
        name: 'GRE',
        desc: 'GRE考试核心词汇',
        total: 12000
      },
      {
        id: 'high_school',
        name: '高中英语',
        desc: '高中英语核心词汇',
        total: 3500
      }
    ],
    
    // 弹窗状态
    showWordbookModal: false,
    showTargetModal: false,
    
    // 每日目标选项
    targetOptions: [10, 15, 20, 30, 50, 100],
    customTarget: '',
    
    // 学习按钮状态
    canStudy: true,
    studyBtnText: '开始学习',
    studyBtnSubtitle: '今日还需学习20个单词',
    
    // 单词本
    activeTab: 'collected',
    notebookCount: 0,
    collectedWords: [],
    difficultWords: [],
    wrongWords: [],
    currentNotebookWords: [],
    
    // 学习记录
    recentRecords: []
  },

  onLoad: function(options) {
    this.loadUserData();
    this.loadNotebookWords();
    this.loadStudyRecords();
    this.updateStudyButton();
  },

  onShow: function() {
    // 页面显示时刷新数据
    this.loadNotebookWords();
    this.updateStudyButton();
  },

  // 加载用户数据
  loadUserData: function() {
    const userSettings = wx.getStorageSync('userSettings') || {};
    const studyStats = wx.getStorageSync('studyStats') || {};
    const today = this.formatDate(new Date());
    
    // 加载设置
    this.setData({
      dailyTarget: userSettings.dailyTarget || 20,
      currentWordbook: userSettings.currentWordbook || this.data.currentWordbook
    });
    
    // 加载今日学习数据
    const todayStats = studyStats[today] || { learned: 0 };
    const totalLearned = Object.values(studyStats).reduce((total, dayStats) => {
      return total + (dayStats.learned || 0);
    }, 0);
    
    const progressPercent = Math.min(100, Math.round((todayStats.learned / this.data.dailyTarget) * 100));
    
    this.setData({
      todayLearned: todayStats.learned,
      totalLearned: totalLearned,
      progressPercent: progressPercent
    });
  },

  // 加载单词本数据
  loadNotebookWords: function() {
    const collectedWords = this.getStorageWords('wordCollections');
    const difficultWords = this.getStorageWords('difficultWords');
    const wrongWords = this.getStorageWords('wrongWords');
    
    const notebookCount = collectedWords.length + difficultWords.length + wrongWords.length;
    
    // 根据当前标签获取对应的单词列表
    const { activeTab } = this.data;
    let currentNotebookWords = [];
    switch (activeTab) {
      case 'collected':
        currentNotebookWords = collectedWords.slice(0, 5);
        break;
      case 'difficult':
        currentNotebookWords = difficultWords.slice(0, 5);
        break;
      case 'wrong':
        currentNotebookWords = wrongWords.slice(0, 5);
        break;
      default:
        currentNotebookWords = collectedWords.slice(0, 5); // 默认显示收藏的词
    }
    
    this.setData({
      collectedWords: collectedWords,
      difficultWords: difficultWords,
      wrongWords: wrongWords,
      notebookCount: notebookCount,
      currentNotebookWords: currentNotebookWords
    });
  },

  // 获取存储的单词数据
  getStorageWords: function(key) {
    const words = wx.getStorageSync(key) || [];
    return words.map(word => {
      if (typeof word === 'string') {
        // 兼容旧格式
        return {
          word: word,
          meaning: '暂无释义',
          addTime: '未知'
        };
      }
      return word;
    });
  },

  // 获取当前标签的单词列表
  getCurrentNotebookWords: function() {
    const { activeTab, collectedWords, difficultWords, wrongWords } = this.data;
    
    switch (activeTab) {
      case 'collected':
        return collectedWords ? collectedWords.slice(0, 5) : []; // 只显示前5个
      case 'difficult':
        return difficultWords ? difficultWords.slice(0, 5) : [];
      case 'wrong':
        return wrongWords ? wrongWords.slice(0, 5) : [];
      default:
        return collectedWords ? collectedWords.slice(0, 5) : []; // 默认显示收藏的词
    }
  },

  // 加载学习记录
  loadStudyRecords: function() {
    const studyStats = wx.getStorageSync('studyStats') || {};
    const records = [];
    
    // 获取最近7天的记录
    for (let i = 0; i < 7; i++) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      const dateStr = this.formatDate(date);
      const dayStats = studyStats[dateStr];
      
      if (dayStats && dayStats.learned > 0) {
        records.push({
          date: this.formatDisplayDate(date),
          count: dayStats.learned,
          duration: dayStats.duration || 0
        });
      }
    }
    
    this.setData({
      recentRecords: records.slice(0, 3) // 只显示最近3条
    });
  },

  // 更新学习按钮状态
  updateStudyButton: function() {
    const { todayLearned, dailyTarget } = this.data;
    const remaining = dailyTarget - todayLearned;
    
    if (remaining <= 0) {
      this.setData({
        studyBtnText: '今日目标已完成',
        studyBtnSubtitle: '继续学习巩固记忆',
        canStudy: true
      });
    } else {
      this.setData({
        studyBtnText: '开始学习',
        studyBtnSubtitle: `今日还需学习${remaining}个单词`,
        canStudy: true
      });
    }
  },

  // 显示单词书选择弹窗
  showWordbookPicker: function() {
    this.setData({ showWordbookModal: true });
  },

  hideWordbookModal: function() {
    this.setData({ showWordbookModal: false });
  },

  preventClose: function() {
    // 阻止事件冒泡，防止弹窗关闭
  },

  // 选择单词书
  selectWordbook: function(e) {
    const wordbookId = e.currentTarget.dataset.id;
    const selectedWordbook = this.data.wordbookList.find(book => book.id === wordbookId);
    
    if (selectedWordbook) {
      this.setData({
        currentWordbook: selectedWordbook,
        showWordbookModal: false
      });
      
      // 保存到本地存储
      const userSettings = wx.getStorageSync('userSettings') || {};
      userSettings.currentWordbook = selectedWordbook;
      wx.setStorageSync('userSettings', userSettings);
      
      wx.showModal({
        title: '切换成功',
        content: `已切换到"${selectedWordbook.name}"`,
        showCancel: false,
        confirmText: '确定'
      });
    }
  },

  // 显示每日目标设置弹窗
  showTargetPicker: function() {
    this.setData({ showTargetModal: true });
  },

  hideTargetModal: function() {
    this.setData({ showTargetModal: false });
  },

  // 选择每日目标
  selectTarget: function(e) {
    const target = parseInt(e.currentTarget.dataset.target);
    this.updateDailyTarget(target);
  },

  // 自定义目标输入
  onCustomTargetInput: function(e) {
    this.setData({
      customTarget: e.detail.value
    });
  },

  // 确认自定义目标
  confirmCustomTarget: function() {
    const target = parseInt(this.data.customTarget);
    if (target && target > 0 && target <= 200) {
      this.updateDailyTarget(target);
    } else {
      wx.showToast({
        title: '请输入1-200之间的数字',
        icon: 'none'
      });
    }
  },

  // 更新每日目标
  updateDailyTarget: function(target) {
    this.setData({
      dailyTarget: target,
      showTargetModal: false,
      customTarget: '',
      progressPercent: Math.min(100, Math.round((this.data.todayLearned / target) * 100))
    });
    
    // 保存到本地存储
    const userSettings = wx.getStorageSync('userSettings') || {};
    userSettings.dailyTarget = target;
    wx.setStorageSync('userSettings', userSettings);
    
    this.updateStudyButton();
    
    wx.showModal({
      title: '设置成功',
      content: `每日目标已设为${target}个单词`,
      showCancel: false,
      confirmText: '确定'
    });
  },

  // 开始学习
  startStudy: function() {
    if (!this.data.canStudy) {
      return;
    }
    
    // 跳转到学习页面
    wx.navigateTo({
      url: '/pages/word-study/word-study'
    });
  },

  // 切换单词本标签
  switchTab: function(e) {
    const tab = e.currentTarget.dataset.tab;
    const { collectedWords, difficultWords, wrongWords } = this.data;
    
    // 根据选择的标签获取对应的单词列表
    let currentNotebookWords = [];
    switch (tab) {
      case 'collected':
        currentNotebookWords = collectedWords.slice(0, 5);
        break;
      case 'difficult':
        currentNotebookWords = difficultWords.slice(0, 5);
        break;
      case 'wrong':
        currentNotebookWords = wrongWords.slice(0, 5);
        break;
      default:
        currentNotebookWords = [];
    }
    
    this.setData({
      activeTab: tab,
      currentNotebookWords: currentNotebookWords
    });
  },

  // 跳转到单词详情
  goToWordDetail: function(e) {
    const word = e.currentTarget.dataset.word;
    wx.navigateTo({
      url: `/pages/word-detail/word-detail?word=${word}`
    });
  },

  // 删除单词本中的单词
  deleteNotebookWord: function(e) {
    e.stopPropagation(); // 阻止事件冒泡
    
    const word = e.currentTarget.dataset.word;
    const type = e.currentTarget.dataset.type;
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除单词"${word}"吗？`,
      success: (res) => {
        if (res.confirm) {
          this.removeWordFromNotebook(word, type);
        }
      }
    });
  },

  // 从单词本中移除单词
  removeWordFromNotebook: function(word, type) {
    let storageKey = '';
    switch (type) {
      case 'collected':
        storageKey = 'wordCollections';
        break;
      case 'difficult':
        storageKey = 'difficultWords';
        break;
      case 'wrong':
        storageKey = 'wrongWords';
        break;
      default:
        return;
    }
    
    const words = wx.getStorageSync(storageKey) || [];
    const filteredWords = words.filter(item => {
      const wordText = typeof item === 'string' ? item : item.word;
      return wordText !== word;
    });
    
    wx.setStorageSync(storageKey, filteredWords);
    this.loadNotebookWords();
    
    wx.showToast({
      title: '已删除',
      icon: 'success'
    });
  },

  // 跳转到完整单词本页面
  goToNotebook: function() {
    wx.navigateTo({
      url: '/pages/notebook/notebook'
    });
  },

  // 显示所有学习记录
  showAllRecords: function() {
    wx.navigateTo({
      url: '/pages/study-records/study-records'
    });
  },

  // 格式化日期
  formatDate: function(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 格式化显示日期
  formatDisplayDate: function(date) {
    const today = new Date();
    const diffTime = today.getTime() - date.getTime();
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays === 1) {
      return '今天';
    } else if (diffDays === 2) {
      return '昨天';
    } else if (diffDays === 3) {
      return '前天';
    } else {
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${month}月${day}日`;
    }
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  }
}) 